#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mqtt_handler.h"

void mqtt_init(MQTTClient* client, MQTTClient_messageArrived* msgarrvd) {
    MQTTClient_create(client, MQTT_ADDRESS, CLIENTID,
        MQTTCLIENT_PERSISTENCE_NONE, NULL);
    
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    
    if (MQTTClient_connect(*client, &conn_opts) != MQTTCLIENT_SUCCESS) {
        fprintf(stderr, "MQTT connection failed\n");
        exit(EXIT_FAILURE);
    }
    
    // 设置消息到达回调
    MQTTClient_setCallbacks(*client, NULL, NULL, msgarrvd, NULL);

    // 添加连接状态检查
    int rc = MQTTClient_connect(*client, &conn_opts);
    if (rc != MQTTCLIENT_SUCCESS) {
        fprintf(stderr, "MQTT连接失败! 错误码: %d\n", rc);
        if (rc == 1) fprintf(stderr, "错误: 连接被拒绝 - 协议版本错误\n");
        else if (rc == 2) fprintf(stderr, "错误: 连接被拒绝 - 客户端ID无效\n");
        else if (rc == 3) fprintf(stderr, "错误: 连接被拒绝 - 服务器不可用\n");
        else if (rc == 4) fprintf(stderr, "错误: 连接被拒绝 - 用户名或密码错误\n");
        else if (rc == 5) fprintf(stderr, "错误: 连接被拒绝 - 未授权\n");
        else fprintf(stderr, "未知错误\n");
        return;
    }
    printf("MQTT连接成功!\n");
}

void mqtt_publish(MQTTClient client, const char* topic, const char* payload) {
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    pubmsg.payload = (void*)payload;
    pubmsg.payloadlen = (int)strlen(payload);
    pubmsg.qos = QOS;
    pubmsg.retained = 0;
    
    MQTTClient_deliveryToken token;
    MQTTClient_publishMessage(client, topic, &pubmsg, &token);
    MQTTClient_waitForCompletion(client, token, TIMEOUT);
}

void mqtt_subscribe(MQTTClient client, const char* topic) {
    int rc = MQTTClient_subscribe(client, topic, QOS);
    if (rc != MQTTCLIENT_SUCCESS) {
        fprintf(stderr, "订阅主题 %s 失败! 错误码: %d\n", topic, rc);
    } else {
        printf("成功订阅主题: %s\n", topic);
    }
}

void mqtt_cleanup(MQTTClient client) {
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
}